<?php
session_start();

// 检查是否已配置数据库
if (!isset($_SESSION['db_config']) || !isset($_SESSION['db_test']) || !$_SESSION['db_test']['success']) {
    header('Location: database.php');
    exit;
}

// 执行安装
if (!isset($_SESSION['install_complete'])) {
    $config = $_SESSION['db_config'];
    
    try {
        // 连接数据库
        $dsn = "mysql:host={$config['host']};dbname={$config['database']};charset={$config['charset']}";
        $pdo = new PDO($dsn, $config['username'], $config['password']);
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        
        // 读取SQL文件并执行
        $sqlFile = __DIR__ . '/../sql/database.sql';
        if (file_exists($sqlFile)) {
            $sql = file_get_contents($sqlFile);
            
            // 先删除已存在的表
            $tables = ['users', 'attendance_records', 'system_config', 'overtime_records', 'leave_records', 'business_trips'];
            foreach ($tables as $table) {
                try {
                    $pdo->exec("DROP TABLE IF EXISTS `{$table}`");
                } catch (Exception $e) {
                    // 忽略删除表时的错误
                }
            }
            
            // 分割SQL语句
            $queries = array_filter(array_map('trim', explode(';', $sql)));
            
            foreach ($queries as $query) {
                if (!empty($query)) {
                    $pdo->exec($query);
                }
            }
        } else {
            throw new Exception('数据库SQL文件不存在');
        }
        
        // 创建管理员账号
        $adminPassword = 'admin123';
        $hashedPassword = password_hash($adminPassword, PASSWORD_DEFAULT);
        
        $stmt = $pdo->prepare("INSERT INTO users (username, password, role, email, full_name, department, position, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
        $stmt->execute([
            'admin',
            $hashedPassword,
            'super_admin',
            'admin@example.com',
            '系统管理员',
            'IT部门',
            '系统管理员',
            1
        ]);
        
        // 确保assets子目录存在
        $assetsSubDirs = ['css', 'images', 'js'];
        foreach ($assetsSubDirs as $subDir) {
            $dirPath = __DIR__ . '/../assets/' . $subDir;
            if (!file_exists($dirPath)) {
                if (!mkdir($dirPath, 0755, true)) {
                    throw new Exception('无法创建assets子目录: ' . $subDir);
                }
            }
        }
        
        // 创建配置文件
        $configContent = "<?php\nreturn [\n    'db' => [\n";
        foreach ($config as $key => $value) {
            $configContent .= "        '{$key}' => '{$value}',\n";
        }
        $configContent .= "    ],\n    'system' => [\n        'title' => '考勤管理系统',\n        'version' => '1.0.0',\n        'debug' => false\n    ]\n];\n";
        
        if (file_put_contents(__DIR__ . '/../config.inc.php', $configContent) === false) {
            throw new Exception('无法创建配置文件');
        }
        
        $_SESSION['install_complete'] = true;
        $_SESSION['install_message'] = '系统安装成功！';
        
    } catch (Exception $e) {
        $_SESSION['install_complete'] = false;
        $_SESSION['install_message'] = '安装失败: ' . $e->getMessage();
    }
}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>考勤管理系统 - 系统安装</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        body {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
        }
        .install-container {
            background: white;
            border-radius: 15px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.2);
            overflow: hidden;
        }
        .install-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 2rem;
            text-align: center;
        }
        .install-body {
            padding: 2rem;
        }
        .step-indicator {
            display: flex;
            justify-content: space-between;
            margin-bottom: 2rem;
            position: relative;
        }
        .step-indicator::before {
            content: '';
            position: absolute;
            top: 20px;
            left: 0;
            right: 0;
            height: 2px;
            background: #e9ecef;
            z-index: 1;
        }
        .step {
            text-align: center;
            position: relative;
            z-index: 2;
        }
        .step-number {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: #e9ecef;
            color: #6c757d;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 0.5rem;
            font-weight: bold;
        }
        .step.active .step-number {
            background: #667eea;
            color: white;
        }
        .step.completed .step-number {
            background: #28a745;
            color: white;
        }
        .step-label {
            font-size: 0.875rem;
            color: #6c757d;
        }
        .step.active .step-label {
            color: #667eea;
            font-weight: bold;
        }
        .install-progress {
            margin: 2rem 0;
        }
        .progress {
            height: 10px;
        }
        .install-steps {
            margin: 2rem 0;
        }
        .install-step {
            padding: 1rem;
            border-left: 4px solid #e9ecef;
            margin-bottom: 1rem;
        }
        .install-step.success {
            border-left-color: #28a745;
            background-color: #f8fff9;
        }
        .install-step.error {
            border-left-color: #dc3545;
            background-color: #fff5f5;
        }
        .install-step.running {
            border-left-color: #007bff;
            background-color: #f0f8ff;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-md-8 col-lg-6">
                <div class="install-container">
                    <div class="install-header">
                        <h1><i class="fas fa-clock me-2"></i>考勤管理系统</h1>
                        <p class="mb-0">安装向导</p>
                    </div>
                    
                    <div class="install-body">
                        <!-- 步骤指示器 -->
                        <div class="step-indicator">
                            <div class="step completed">
                                <div class="step-number"><i class="fas fa-check"></i></div>
                                <div class="step-label">环境检测</div>
                            </div>
                            <div class="step completed">
                                <div class="step-number"><i class="fas fa-check"></i></div>
                                <div class="step-label">数据库配置</div>
                            </div>
                            <div class="step active">
                                <div class="step-number">3</div>
                                <div class="step-label">系统安装</div>
                            </div>
                            <div class="step">
                                <div class="step-number">4</div>
                                <div class="step-label">完成安装</div>
                            </div>
                        </div>

                        <h3 class="mb-4">系统安装</h3>
                        
                        <?php if (isset($_SESSION['install_complete'])): ?>
                            <?php if ($_SESSION['install_complete']): ?>
                                <div class="alert alert-success">
                                    <i class="fas fa-check-circle me-2"></i>
                                    <?php echo $_SESSION['install_message']; ?>
                                </div>
                                
                                <div class="install-steps">
                                    <div class="install-step success">
                                        <i class="fas fa-check text-success me-2"></i>
                                        <strong>数据库连接</strong> - 连接成功
                                    </div>
                                    <div class="install-step success">
                                        <i class="fas fa-check text-success me-2"></i>
                                        <strong>数据表创建</strong> - 所有表创建成功
                                    </div>
                                    <div class="install-step success">
                                        <i class="fas fa-check text-success me-2"></i>
                                        <strong>初始数据导入</strong> - 管理员账号和配置数据导入成功
                                    </div>
                                    <div class="install-step success">
                                        <i class="fas fa-check text-success me-2"></i>
                                        <strong>配置文件生成</strong> - 系统配置文件创建成功
                                    </div>
                                </div>
                                
                                <div class="alert alert-info">
                                    <h5><i class="fas fa-info-circle me-2"></i>默认管理员账号</h5>
                                    <p class="mb-1"><strong>用户名:</strong> admin</p>
                                    <p class="mb-1"><strong>密码:</strong> admin123</p>
                                    <p class="mb-0"><small class="text-muted">请登录后立即修改密码</small></p>
                                </div>
                                
                                <div class="text-end">
                                    <a href="complete.php" class="btn btn-success">
                                        完成安装 <i class="fas fa-check ms-2"></i>
                                    </a>
                                </div>
                            <?php else: ?>
                                <div class="alert alert-danger">
                                    <i class="fas fa-exclamation-triangle me-2"></i>
                                    <?php echo $_SESSION['install_message']; ?>
                                </div>
                                
                                <div class="install-steps">
                                    <div class="install-step success">
                                        <i class="fas fa-check text-success me-2"></i>
                                        <strong>数据库连接</strong> - 连接成功
                                    </div>
                                    <div class="install-step error">
                                        <i class="fas fa-times text-danger me-2"></i>
                                        <strong>系统安装</strong> - 安装过程中出现错误
                                    </div>
                                </div>
                                
                                <div class="text-end">
                                    <a href="database.php" class="btn btn-warning">
                                        <i class="fas fa-redo me-2"></i>重新安装
                                    </a>
                                </div>
                            <?php endif; ?>
                        <?php else: ?>
                            <div class="text-center">
                                <div class="spinner-border text-primary mb-3" role="status">
                                    <span class="visually-hidden">安装中...</span>
                                </div>
                                <p>正在安装系统，请稍候...</p>
                            </div>
                            
                            <script>
                                setTimeout(function() {
                                    location.reload();
                                }, 1000);
                            </script>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
